import React, { Component } from 'react'
import { StyleSheet, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { Entity, IconButton } from '../components'
import store from '../store'

@inject('actions', 'store')
@observer
@graphql(
  gql`
    query($id: ID!) {
      User(id: $id) {
        id
        username
        name
        role
        createdAt
        updatedAt
      }
    }
  `,
  {
    options: ({ navigation }) => ({
      variables: { id: navigation.getParam('id') || store.user.id },
    }),
  },
)
@graphql(
  gql`
    mutation($id: ID!, $username: String!, $name: String!) {
      updateUser(id: $id, username: $username, name: $name) {
        id
      }
    }
  `,
  { name: 'update' },
)
export class ProfileScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerRight: navigation.getParam('editing') ? (
      <IconButton
        name="close"
        onPress={() => navigation.setParams({ editing: false })}
      />
    ) : (
      <IconButton
        name="build"
        onPress={() => navigation.setParams({ editing: true })}
      />
    ),
  })

  get data() {
    const key = 'User'
    const loaded = this.props.data && !this.props.data.loading
    return loaded ? this.props.data[key] : {}
  }

  onSubmit = async data => {
    const { navigation, store, update } = this.props

    await update({
      variables: {
        ...data,
        id: navigation.getParam('id') || this.props.store.user.id,
      },
    })

    await this.props.data.refetch()

    if (this.props.store.user.id === this.data.id) {
      this.props.store.user.username = this.data.username
      this.props.store.user.name = this.data.name
    }

    navigation.setParams({ editing: false })
  }

  render = () => (
    <View style={styles.container}>
      <Entity
        editing={this.props.navigation.getParam('editing')}
        data={this.data}
        onSubmit={this.onSubmit}
        schema={[
          { key: 'id', label: 'ID', wrap: true },
          { key: 'username', label: 'Username', editable: true },
          { key: 'name', label: 'Display Name', editable: true },
          { key: 'role', label: 'Role' },
        ]}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})
